package com.canal.display.handler;

import com.alibaba.fastjson.JSONObject;
import com.canal.display.entity.TokenBasedAuthentication;
import com.canal.display.service.UserTokenService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 在成功认证token之后，检查是否需要刷新token
 * @author Administrator
 * @description
 * @date 2019年03月17 15:02
 */
public class TokenRefreshSuccessHandler implements AuthenticationSuccessHandler {

    private UserTokenService userTokenService;

    public TokenRefreshSuccessHandler(UserTokenService userTokenService) {
        this.userTokenService = userTokenService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        TokenBasedAuthentication tokenBasedAuthentication = ((TokenBasedAuthentication)authentication);
        //这里只是刷新了token的过期时间，如果要更改token，则需要rename之后重新写入数据，并将新的token返回给前端，一般放置在header中
        String token = tokenBasedAuthentication.getToken();
        String refreshTime = userTokenService.refreshTime(token);
        long refreshTimeLong = Long.valueOf(refreshTime);
        if(refreshTimeLong <= System.currentTimeMillis()) {
            //刷新token
            Map<String, String> userMap = new HashMap<>(4);
            userMap.put("username", ((UserDetails) tokenBasedAuthentication.getPrincipal()).getUsername());
            //设置token刷新时间，超过这个时间就刷新
            userMap.put("refreshTime",(System.currentTimeMillis()+5*60*1000)+"");
            String jsonStr = JSONObject.toJSONString(userMap);
            userTokenService.setTokenToRedis(jsonStr,token);
        }
    }
}
